//
//  DSUnitExerciseController.m
//  DSJY
//
//  Created by 冯华强 on 16/9/24.
//  Copyright © 2016年 dsjy. All rights reserved.
//  单元练习

#import "DSUnitExerciseController.h"
#import "UIView+Extension.h"
#import "DSUnitInnerView.h"
#import "DSUnitBorderView.h"
#import "XCYAudioTool.h"
#import "DSUnitExerciseResultController.h"
#import "MTNavigationController.h"
#import "MTConst.h"
#import "DSUnitContentView.h"
#import "DSUnitView.h"
#import "DSUnitExerciseViewModel.h"
#import "DSUnit.h"
#import "DSUnitContentViewModel.h"
#import "UIView+Animation.h"
#import "DSAudioView.h"
#import "DSUnitListeningContent.h"
#import "DSUnitSubContent.h"
#import "DSUnitListening.h"
#import "DSUnitExercise.h"
#import "DSAccountViewModel.h"
#import "DSMyLearnInfo.h"
#import "DSUnitExerciseToolbar.h"
#import "DSUnitExerciseResultViewModel.h"
#import "MBProgressHUD+MJ.h"
#import "HMTransition.h"
#import "DSPassCelebrateView.h"
#import "Masonry.h"
#import "DSCourse.h"
#import "NSString+Extension.h"
#import "DSAppResAddressIp.h"

#define tranContentDuration 0.5
#define positionDuration 1.0
#define nextDelayInSeconds 0.5
#define vInnerBgMargin 10
@interface DSUnitExerciseController ()<AVAudioPlayerDelegate, DSUnitExerciseResultControllerDelegate, DSAudioViewDelegate, DSUnitExerciseToolbarDelegate, CAAnimationDelegate>
#pragma mark - 拖线属性
//音乐背景View
@property (weak, nonatomic) IBOutlet DSAudioView *audioBgView;
//内容View
@property (weak, nonatomic) IBOutlet DSUnitContentView *unitContentView;
//内容View
@property (weak, nonatomic) IBOutlet UIView *contentView;
//工具条
@property (weak, nonatomic) IBOutlet DSUnitExerciseToolbar *toolbar;
//单元练习VM
@property (nonatomic, strong) DSUnitExerciseViewModel *unitExerciseVM;
//单元练习内容VM
@property (nonatomic, strong) DSUnitContentViewModel *unitContentVM;
//单元中的所有音频
@property (nonatomic, strong) NSMutableArray<DSUnitListeningContent *> *audioList;
//当前音频的下标
@property (nonatomic, assign) NSInteger currentIndex;
//显示的DSUnitContentView中DSUnitView的个数
@property (nonatomic, assign) NSInteger pictures;
//答题记录
@property (nonatomic, strong) NSMutableDictionary<NSNumber *, NSNumber *> *exercisDict;
//我的成绩
@property (nonatomic, strong) DSMyLearnInfo *myLearnInfo;
//答题结果
@property (nonatomic, strong) DSUnitExerciseResultViewModel *exerciseResultVM;
//当前单元的Id
@property (nonatomic, strong) NSString *unitId;
//通关的，放烟花庆祝
@property(nonatomic, weak) DSPassCelebrateView *passCelebrateView;
//下载的index
@property (nonatomic, assign) NSInteger downIndex;
//下载音频失败后启动监视器
@property (nonatomic, strong) NSTimer *timer;
//是否单击图片中
@property (nonatomic, assign, getter=isCurrentClick) BOOL currentClick;
@end

@implementation DSUnitExerciseController

#pragma mark - 懒加载
- (DSUnitExerciseViewModel *)unitExerciseVM
{
    if (_unitExerciseVM == nil) {
        _unitExerciseVM = [[DSUnitExerciseViewModel alloc] initWithUnitId:self.unitId userExist:self.course.userExist];
    }
    return _unitExerciseVM;
}

- (DSUnitContentViewModel *)unitContentVM
{
    if (_unitContentVM == nil) {
        _unitContentVM = [[DSUnitContentViewModel alloc] initWithUnitSubContent:self.unitExerciseVM.unitSubContent];
        
        //能懒加载unitContentVM表示audio不为空,在这里播放第一个音频感觉是最好的
//        self.audioBgView.listeningContent = self.audioList[self.currentIndex];
        self.toolbar.listeningContent = self.audioList[self.currentIndex];
        //设置代理
        self.toolbar.delegate = self;
        //设置标题
        self.toolbar.unitExercise = self.unitExerciseVM.unitExercise;
        [self.toolbar setupTitleIndex:1 totalCount:self.unitExerciseVM.unitSubContent.listening.count];
        //启动时间
        [self.toolbar startTimerWithMinute:self.unitExerciseVM.unitSubContent.maxTime pictures:self.pictures];
    }
    return _unitContentVM;
}

- (NSMutableArray<DSUnitListeningContent *> *)audioList
{
    return self.unitExerciseVM.audioList;
}

- (NSMutableDictionary<NSNumber *, NSNumber *> *)exercisDict
{
    if (_exercisDict == nil) {
        _exercisDict = [NSMutableDictionary<NSNumber *, NSNumber *> dictionary];
    }
    return _exercisDict;
}

- (DSUnitExerciseResultViewModel *)exerciseResultVM
{
    if (_exerciseResultVM == nil) {
        _exerciseResultVM = [[DSUnitExerciseResultViewModel alloc] init];
    }
    return _exerciseResultVM;
}

- (DSPassCelebrateView *)passCelebrateView
{
    if (_passCelebrateView == nil) {
        //通关的，放烟花庆祝
        DSPassCelebrateView *passCelebrateView = [DSPassCelebrateView passCelebrateView];
        [self.view addSubview:passCelebrateView];
        _passCelebrateView = passCelebrateView;
        
        [passCelebrateView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.mas_equalTo(0);
            make.top.equalTo(self.unitContentView);
            make.height.mas_equalTo(PassCelebrateViewH);
        }];
    }
    return _passCelebrateView;
}

#pragma mark - 系统回调
- (void)viewDidLoad {
    [super viewDidLoad];
    
    //显示backItem
    [self setupnavigationItem];
    //初始化信息
    [self initialBind];
    //绑定事件
    [self bindEvent];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    //销毁时清除，避免循环引用
    [self clearAll];
}

- (void)dealloc
{
//    [self.audioBgView stopMusic];
//    self.audioBgView.delegate = nil;
    [self clearAll];
    [self.toolbar stopMusic];
    [self.toolbar invalidate];
    self.toolbar.delegate = nil;
    [SVProgressHUD dismiss];
    MTLog(@"%s", __func__);
}

- (void)setUnit:(DSUnit *)unit
{
    _unit = unit;
    
    //第一次的时候记录单元Id
    self.unitId = unit.unitId;
}

- (NSTimer *)setupTimer
{
    _timer = [NSTimer timerWithTimeInterval:1.0f target:self selector:@selector(doPay) userInfo:@"timer" repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
    return _timer;
}

- (void)setAppResourceAddressIp:(NSString *)appResourceAddressIp
{
    _appResourceAddressIp = appResourceAddressIp;
    
    NSArray *appIds = [DSAppResAddressIp sharedInstance].appIds;
    NSString *appId = [MTUserDefaults objectForKey:appIds_key];
    NSString *address = @"";
    if (appIds != nil && appIds.count > 0 && [NSString isNotEmptyWithStr:appId]) {
        address = appId;
    }else{
        address = [NSString isNotEmptyWithStr:appResourceAddressIp] ? appResourceAddressIp : DSExerciseDomain;
    }
    //address = DSExerciseDomain; //测试写死
    [MTUserDefaults setObject:[address trim] forKey:DSExerciseDomainAddress];
    [MTUserDefaults synchronize];
}

#pragma mark - 设置UI
- (void)setupnavigationItem
{
    self.showBackItem = YES;
}

- (void)clearAll
{
//    self.unitExerciseVM = nil;
    self.unitContentVM = nil;
    self.exercisDict = nil;
    self.exerciseResultVM = nil;
    self.unitContentView.unitContentVM = nil;
    [self.passCelebrateView removeFromSuperview];
    self.passCelebrateView = nil;
    [XCYAudioTool stopAllMusic];
}

//初始化信息
- (void)initialBind
{
    //音乐的图片点击代理
//    self.audioBgView.delegate = self;
    self.toolbar.delegate = self;
}

#pragma mark - 设置事件
- (void)bindEvent
{
    @weakify(self);
    //加载成功后，请求加载成功
    [self.unitExerciseVM.requestSuccessSignal subscribeNext:^(id x) {
        @strongify(self);
        //记录当前的unitid，重播的时候有用
        self.unitId = self.unitExerciseVM.unitExercise.unitid;
        self.unitExerciseVM.unitId = self.unitId;
        //标志当前音频的下标为0
        self.currentIndex = 0;
        //恢复图像、音频可以点击
        self.unitContentView.userInteractionEnabled = YES;
        self.unitContentView.pictures = self.unitExerciseVM.unitSubContent.pictures;
        self.toolbar.userInteractionEnabled = YES;
        //记录当前的题的数，要显示多少个DSUnitView
        self.pictures = self.unitExerciseVM.unitSubContent.pictures;
        //记录当前的时间
        self.toolbar.timeLabel.text = self.unitExerciseVM.unitSubContent.maxTimeString;
    }];
    
    //音频下载后，触发刷新第一个对象
    [self.unitExerciseVM.audioDownloadCommand.executionSignals.switchToLatest subscribeNext:^(id x) {
        @strongify(self);
        if ([x isKindOfClass:[NSError class]]){
            self.downIndex = self.downIndex;  //重新下载
            return;
        }
        //显示音频的背景View
//        self.audioBgView.hidden = NO;
        NSInteger curIndex = [x integerValue];
        if (curIndex == 1) {  //这里这样做是因为VM一开始下载的是两个
            curIndex += 1;
        }
        if (self.audioList.count > curIndex) {
            self.downIndex = curIndex;
        }
        
        if ([x integerValue] != 1) {
            return;
        }
        MTLog(@"==================");
        //赋值unitContentVM
        self.unitContentView.unitContentVM = self.unitContentVM;
        //判断是否故事会
        [self playStoryUnitWithDuration:0.0];
    }];
    
    //监听图片点击
    [[[MTNotificationCenter rac_addObserverForName:DSUnitInnerViewDidIconViewClickNote object:nil] takeUntil:self.rac_willDeallocSignal] subscribeNext:^(NSNotification *note) {
        @strongify(self);
        
        AVAudioPlayer *player = self.toolbar.player;
        NSTimeInterval diff = player.duration - player.currentTime;
        //获取当前播放的音频
        DSUnitListeningContent *currentListeningContent = self.audioList[self.currentIndex];
        NSString *first = [[[currentListeningContent.src lastPathComponent] substringWithRange:NSMakeRange(0, 1)] uppercaseString];
        if (player.playing && diff > 0.5 && ![@"Z" isEqualToString:first]) {
//            [SVProgressHUD showText:@"请听完再选择" font:setFont18];
            [MBProgressHUD showText:@"请听完再选择" view:self.view];
            return;
        }
        
        if (self.isCurrentClick) return;
        
        //先禁止获取事件
        DSUnitInnerView *unitInnerView = note.object;
        DSUnitListeningContent *listeningContent = unitInnerView.listeningContent;
        self.unitContentView.userInteractionEnabled = NO;
        self.currentClick = YES;
        
        //答对题
        BOOL isRight = [listeningContent.name isEqualToString:currentListeningContent.name];
        unitInnerView.right = isRight;
        //记录对错
        NSNumber *right = self.exercisDict[@(self.currentIndex)];
        if (right == nil) {
            [self.exercisDict setObject:@(isRight) forKey:@(self.currentIndex)];
            self.toolbar.exercisDict = self.exercisDict;
        }
        if (isRight) {
            //停止音乐
//            [self.audioBgView stopMusic];
            [self.toolbar stopMusic];
            //答对题的时候才需要移动
//            [self.view positionLayerView:self.audioBgView toView:unitInnerView delegateVC:self];
            [self doNextExerciseAndInsertMyLearn];
        }else{ //答错题
            //需要重新播放一下音频
//            [self.audioBgView stopToPlayMusic];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.toolbar stopToPlayMusic];
                self.unitContentView.userInteractionEnabled = YES;
            });
        }
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.currentClick = NO;
        });
    }];
    
    //上传分数
    [self.unitExerciseVM.insertMyLearninginfoCommand.executionSignals.switchToLatest subscribeNext:^(id x) {
        @strongify(self);
        if ([x isKindOfClass:[NSError class]]) return ;
        
        if (self.toolbar.score >= 90){
            //学习通关后刷新单元列表
            [MTNotificationCenter postNotificationName:DSLearnPassDidRefreshUnitListNote object:nil];
        }
        
        if ([x integerValue] >= 100) {
            NSString *msg = [NSString stringWithFormat:@"恭喜你！因为连续闯关活动100分，已经自动为你解锁到%@关，你可以跳过这些关闯下一关！", x];
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:msg preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                [self doUnitExerciseResult];
            }];
            [alertController addAction:cancelAction];
            
            [self presentViewController:alertController animated:YES completion:nil];
        }else{
            [self doUnitExerciseResult];
        }
        
    }];
    
    //执行请求
    [self.unitExerciseVM.requestCommand execute:nil];
}

- (void)doUnitExerciseResult
{
    dispatch_async(dispatch_get_main_queue(), ^{
        //修改练习结果VM
        self.exerciseResultVM.unitExercise = self.unitExerciseVM.unitExercise;
        self.exerciseResultVM.myLearnInfo = self.myLearnInfo;
        NSInteger rightCount = [self.toolbar.rightButton.currentTitle integerValue];
        self.exerciseResultVM.rightCount = rightCount;
        self.exerciseResultVM.wrongCount = self.unitExerciseVM.unitSubContent.listening.count * self.pictures - rightCount;
        
        //弹出提示框，最后试题到时间的提示
        DSUnitExerciseResultController *regionVc = [[DSUnitExerciseResultController alloc] init];
        regionVc.exerciseResultVM = self.exerciseResultVM;
        regionVc.modalPresentationStyle = UIModalPresentationCustom;
        regionVc.delegate = self;
        HMTransition *transition = [HMTransition sharedTransition];
        //        CGFloat unitExerciseResultH = self.unitExerciseVM.unitExercise.exerciseType == DSUnitExerciseTypeNormal ? unitExerciseResultNormalH : unitExerciseResultStoryH;
        transition.presentedViewSize = CGSizeMake(510, unitExerciseResultNormalH);
        regionVc.transitioningDelegate = transition;
        [self presentViewController:regionVc animated:YES completion:nil];

    });
}

- (void)playStoryUnitWithDuration:(NSTimeInterval)duration
{
    //判断是否是故事会
    if (self.unitExerciseVM.unitExercise.exerciseType != DSUnitExerciseTypeStory) return;
    
    //故事会禁止点击
    self.unitContentView.userInteractionEnabled = NO;
    self.toolbar.userInteractionEnabled = NO;
    duration += 0.001;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(duration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        //传递故事会对象，让borderView选中
        self.unitContentView.stroyListeningContent = self.audioList[self.currentIndex];
    });
}

- (void)setDownIndex:(NSInteger)downIndex
{
    _downIndex = downIndex;
    
    //连续下载音频
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.unitExerciseVM.audioDownloadCommand execute:self.audioList[downIndex]];
            });
        });
    });
}

#pragma mark - 设置动画
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
    if (flag && [anim isKindOfClass:[CABasicAnimation class]]) {
        //判断当前的audio是否已经完成一个节奏，即audioList中全部完成
        
//        [self doNextExerciseAndInsertMyLearn];
    }
}

- (void)doNextExerciseAndInsertMyLearn
{
    if (self.audioList.count <= self.currentIndex + 1) { //已经做完所有题
        MTLog(@"已完成所有题");
        
        [self invalidateAndInsertMyLearninginfo];
    }else{
        [self doNextExercise];
    }
}

- (void)doPay
{
    DSUnitListeningContent *listeningContent = self.audioList[self.currentIndex];
    if ([NSString isEmptyWithStr:listeningContent.filePath]) {
        //下载失败，启动监视器
        if (self.timer == nil) {
            [SVProgressHUD showWithStatus:@"下载音频中，请稍等..."];
            [self setupTimer];
        }
    }else{
        //已经下载了就停止事件和提示
        [self.timer invalidate];
        self.timer = nil;
        [SVProgressHUD dismiss];
        //先进行下一题操作
        NSTimeInterval duration = [self doNextExercisePayAudio];
        //故事会
        [self playStoryUnitWithDuration:duration];
    }
}

//下一题
- (NSTimeInterval)doNextExercise
{
    //先停止播发音频(防止重复播放)
//    [self.toolbar stopMusic];
    [XCYAudioTool stopAllMusic];
    
    //累加下标
    self.currentIndex++;
    
    //下载当前题的下一道题
//    if (self.audioList.count > self.currentIndex + 1) {
//        [self.unitExerciseVM.audioDownloadCommand execute:self.audioList[self.currentIndex+1]];
//    }
    
    DSUnitListeningContent *listeningContent = self.audioList[self.currentIndex];
    if ([NSString isEmptyWithStr:listeningContent.filePath]) {
        //下载失败，启动监视器
        [self doPay];
        return nextDelayInSeconds;
    }
    
    return [self doNextExercisePayAudio];
}

- (NSTimeInterval)doNextExercisePayAudio
{
    //判断是否要进入下一个listening，做专场动画的操作
    BOOL isNextListening = NO;
    if (self.currentIndex % self.pictures == 0) {
        isNextListening = YES;
    }
    
    NSTimeInterval duration = isNextListening ? (nextDelayInSeconds + tranContentDuration * 0.5) : nextDelayInSeconds;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(duration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        //更新并播放音频(里面包含停止)
        //        self.audioBgView.listeningContent = self.audioList[self.currentIndex];
        self.toolbar.listeningContent = self.audioList[self.currentIndex];
        //重新设置可以点击(非故事会)
        if (self.unitExerciseVM.unitExercise.exerciseType != DSUnitExerciseTypeStory) {
            self.unitContentView.userInteractionEnabled = YES;
        }
    });
    
    if (isNextListening) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(nextDelayInSeconds * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            //设置标题
            [self.toolbar setupTitleIndex:self.currentIndex / self.pictures + 1 totalCount:self.unitExerciseVM.unitSubContent.listening.count];
            //执行转场动画
            [self.unitContentView contentTransitionWithContentView:self.contentView delegateVC:self duration:tranContentDuration];
            //更新图片
            self.unitContentVM.listening = self.unitExerciseVM.unitSubContent.listening[self.currentIndex / self.pictures];
            self.unitContentView.unitContentVM = self.unitContentVM;
        });
    }
    return duration;
}

//停止时间、上传分数，并显示分数、对错提示框
- (void)invalidateAndInsertMyLearninginfo
{
    //停止时间
    [self.toolbar invalidate];
    
    //判断是否需要播放鼓掌音频和放烟花
    [self setupPassCelebrate];
    
    //上传分数
    [self insertMyLearninginfo];
}

- (void)setupPassCelebrate
{
    if (self.unitExerciseVM.unitExercise.exerciseType == DSUnitExerciseTypeStory) return; //故事会的就直接退出
    if (self.toolbar.score < 90) return;
    
    //播放掌声
    [XCYAudioTool playAudioWithFileName:@"zhangsheng.mp3"];
    
    //放烟花
    [self passCelebrateView];
}

//上传分数，并显示分数、对错提示框
- (void)insertMyLearninginfo
{
    //上传分数
    self.myLearnInfo = [[DSMyLearnInfo alloc] init];
    self.myLearnInfo.studentid = [DSAccountViewModel sharedAccount].account.stuId;
    self.myLearnInfo.unitid = self.unitExerciseVM.unitExercise.unitid;
    self.myLearnInfo.iflastunit = self.unitExerciseVM.unitExercise.nextUnitId == nil;
    self.myLearnInfo.stime = self.toolbar.stime;
    self.myLearnInfo.score = self.toolbar.score;
    
    if ([DSAccountViewModel sharedAccount].account.isUploadScore){ 
        //上传分数
        [self.unitExerciseVM.insertMyLearninginfoCommand execute:self.myLearnInfo];
    }else{
        //提示是否上传分数
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:@"是否确定要上传成绩，确定后后续的成绩都会上传，首页设置中可以进行相关操作!" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            //不上传分数
            [self.unitExerciseVM.insertMyLearninginfoCommand execute:nil];
        }];
        UIAlertAction *submitAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            //修改标识
            [DSAccountViewModel sharedAccount].account.uploadScore = YES;
            [[DSAccountViewModel sharedAccount] write];
            //上传分数
            [self.unitExerciseVM.insertMyLearninginfoCommand execute:self.myLearnInfo];
        }];
        [alertController addAction:cancelAction];
        [alertController addAction:submitAction];
        
        [self presentViewController:alertController animated:YES completion:nil];
    }
    
}

//#pragma mark - <DSAudioViewDelegate>
//- (void)audioViewDidBgViewClick:(DSAudioView *)audioView
//{
//    [audioView stopToPlayMusic];
//}

#pragma mark - <DSUnitExerciseToolbarDelegate>
- (void)unitExerciseToolbarDidAudioButtonClick:(DSUnitExerciseToolbar *)toolbar
{
    [self.toolbar stopToPlayMusic];
}

#pragma mark - <DSUnitExerciseToolbarDelegate>
- (void)unitExerciseToolbarDidTimerUp:(DSUnitExerciseToolbar *)toolbar
{
    [self insertMyLearninginfo];
}

#pragma mark - <AVAudioPlayerDelegate>
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
//    self.audioBgView.audioBtn.selected = NO;
    self.toolbar.audioBtn.selected = NO;
    
     //已经做完所有题
    if (self.audioList.count <= self.currentIndex + 1) {
        if (self.unitExerciseVM.unitExercise.exerciseType == DSUnitExerciseTypeStory){
            [self invalidateAndInsertMyLearninginfo];
        }
        return;
    }
    //故事会的自动下一个
    if (self.unitExerciseVM.unitExercise.exerciseType != DSUnitExerciseTypeStory) return;
    
    //处理故事会的操作
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.05 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        //先进行下一题操作
        NSTimeInterval duration = [self doNextExercise];
        //故事会
        [self playStoryUnitWithDuration:duration];
    });
}

- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError * __nullable)error
{
    MTLog(@"error:%@", error);
}

#pragma mark - <DSUnitExerciseResultControllerDelegate>
//重来
- (void)unitExerciseResultControllerDidResetBtnClick:(DSUnitExerciseResultController *)vc
{
    //清楚所有缓存的数据
    [self clearAll];
    
    //执行请求
    [self.unitExerciseVM.requestCommand execute:nil];
}

//返回
- (void)unitExerciseResultControllerDidBackBtnClick:(DSUnitExerciseResultController *)vc
{
    //延迟关闭，因为DSUnitExerciseResultController要先关闭
    [self dismissViewControllerAnimated:YES completion:nil];
}

//继续
- (void)unitExerciseResultControllerDidNextButtonClick:(DSUnitExerciseResultController *)vc
{
    //清楚所有缓存的数据
    [self clearAll];
    
    //修改为下一个单元的Id
    self.unitExerciseVM.unitId = self.unitExerciseVM.unitExercise.nextUnitId;
    
    //修改self.title
    for (DSUnit *unit in self.unitList) {
        if ([unit.unitId isEqualToString:self.unitExerciseVM.unitId]) {
            self.title = [NSString stringWithFormat:@"%@ > %@", self.course.name, unit.name];
            break;
        }
    }
    
    //执行请求
    [self.unitExerciseVM.requestCommand execute:nil];
}

@end
